package ca.cbc.localsrvextadmin.action;

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.Preparable;
import ca.cbc.giscommon.dao.TwitterUserDAO;
import ca.cbc.giscommon.entity.TwitterUser;
import ca.cbc.giscommon.util.HibernateUtil;
import ca.cbc.giscommon.util.StringUtil;
import ca.cbc.localsrvextadmin.util.ExceptionUtil;

public class ManageTwitterUserAction extends LSEAction implements Preparable {

	private static final long serialVersionUID = -4971222587871222913L;
	private static Logger logger = LoggerFactory.getLogger(ManageTwitterUserAction.class);
	
	private String actiontype = LIST;
	private List<TwitterUser> twitterUserList = null;
	private TwitterUser twitterUser;
	private TwitterUserDAO dao;
	
	public ManageTwitterUserAction () {
		twitterUser = new TwitterUser();
		dao = new TwitterUserDAO();
	}

	public String add() {	
		twitterUser = new TwitterUser();
		twitterUser.setCbcAccount(false);
		
		actiontype = ADD;
		return actiontype;
	}

	public TwitterUser getTwitterUser() {
		return twitterUser;
	}

	public List<TwitterUser> getTwitterUserList() {
		return twitterUserList;
	}

	public String list() throws Exception  {
		this.setTwitterUserList(dao.listByOrder("screenName", true));
		
		actiontype = LIST;
		return actiontype;
	}

	@Override
	public void prepare() throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	public String save() throws Exception {
		if (twitterUser.getScreenName() != null)
				twitterUser.setScreenName(twitterUser.getScreenName().trim());
		
		try {
			dao.saveOrUpdate(twitterUser);
			HibernateUtil.flushAndClear();
		}
		catch (Exception e){
			addActionError("Saving feed failure: " + ExceptionUtil.getRootCauseMessage(e));
			logger.error("Saving feed failure: ", e);
			HibernateUtil.rollbackTransaction();
			return ERROR;
		}
		return SUCCESS;
	}
	
	public void setTwitterUser(TwitterUser twitterUser) {
		this.twitterUser = twitterUser;
	}
	
	public void setTwitterUserList(List<TwitterUser> twitterUserList) {
		this.twitterUserList = twitterUserList;
	}

	// update digest status
	public String update() throws Exception {
		String screenName = getParameter("selectedTwitterUser");
		if(!StringUtil.instance.isNullOrEmpty(screenName)) {
			TwitterUser user = dao.findByField("screenName", screenName);
			if(user != null) {
				user.setCbcAccount(!user.isCbcAccount());
				dao.saveOrUpdate(user);
			}
		}
		return SUCCESS;
	}
}
